﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;
using WebCache = System.Web.Caching.Cache;

namespace mForum.Web.Common.Infrastructure.Cache
{
    using mForum.Core.Common;

    public class Cache : ICache
    {
        private WebCache _cache;
        private readonly object _syncObject = new object();

        public Cache(WebCache cache)
        {
            Check.Argument.IsNotNull(cache, "cache");

            _cache = cache;
        }

        public void Set<T>(string key, object value, DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            DoSet<T>(key, value, absoluteExpiration, slidingExpiration);
        }

        public void Set<T>(string key, object value, DateTime absoluteExpiration)
        {
            DoSet<T>(key, value, absoluteExpiration, WebCache.NoSlidingExpiration);
        }

        public void Set<T>(string key, object value, TimeSpan slidingExpiration)
        {
            DoSet<T>(key, value, WebCache.NoAbsoluteExpiration, slidingExpiration);
        }

        public T Remove<T>(string key)
        {
            return (T) _cache.Remove(key);
        }

        public void Clear()
        {
            IDictionaryEnumerator cacheEnumerator = _cache.GetEnumerator();

            while (cacheEnumerator.MoveNext())
            {
                _cache.Remove(cacheEnumerator.Key.ToString());
            }
        }

        public T Get<T>(string key)
        {
            Check.Argument.IsNotEmpty(key, "key");

            lock (_syncObject)
            {
                T cacheItem = (T)_cache.Get(key);

                if (cacheItem == null)
                    return default(T);
                else
                    return cacheItem;
            }
        }

        private void DoSet<T>(string key, object value, DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            Check.Argument.IsNotEmpty(key, "key");
            Check.Argument.IsNotNull(value, "value");

            if (_cache[key] == null)
                _cache.Add(key, value, null, absoluteExpiration, slidingExpiration, CacheItemPriority.Normal, null);
            else
                _cache.Insert(key, value, null, absoluteExpiration, slidingExpiration);
        }
    }
}
